﻿Imports System.Data
Imports System.Drawing

Public Class frmMain

#Region "Khai bao bien"
    Public dtSet As New DataSet()
    Dim tempGirdMenu As New DataTable()
   

    ' khai bao de dong form login
#End Region

#Region "Cac bien co"
    Private Sub btThoat_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btThoat.Click
        Me.Close()
    End Sub

    Private Sub btThem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btThem.Click
        Dim frm As frmThemNSD = New frmThemNSD(Me)
        frm.ShowDialog()
    End Sub
    Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Me.KeyPreview = True
        Dim frm As New frmLogin(Me)
        frm.ShowDialog()
    End Sub
    Private Sub listNSD_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles listNSD.SelectedIndexChanged
        If (listNSD.SelectedIndex <> -1) Then
            Dim id As Integer = listNSD.SelectedValue
            CapNhatTrangThai(id)
        End If
    End Sub

    Private Sub btCapNhat_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btCapNhat.Click
        capNhatNSD()
    End Sub

    Private Sub capNhatNSD()
        'lay ra nguoi su dung dang duoc chon
        If (listNSD.SelectedIndex <> -1) Then
            Dim user As New CNguoiSuDung()
            user.User_ID = listNSD.SelectedValue
            user.LoginName = listNSD.Text.Trim()
            user.FullName = txtFullName.Text
            user.GhiChu = txtChiTiet.Text
            'cap nhat lai thong tin ve nhom quyen
            If (cboBan.SelectedValue <> Nothing) Then
                user.Nhom_ID = cboBan.SelectedValue
            End If
            Dim viTri As Integer = listNSD.SelectedIndex

            If (dtSet.Tables(s_tblNguoiDung).Rows(viTri)("IsAdmin") = 1) Then
                user.IsAdmin = True
            Else
                user.IsAdmin = False
            End If

            Dim trangThaiSau As Boolean = chkAdmin.Checked
            If user.CapNhat(trangThaiSau) = False Then
                MessageBox.Show("Cập nhật không thành công. Lỗi", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information)
            Else
                MessageBox.Show("Cập nhật thành công!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information)
                'cap nhat lai bang s_tblNguoiDung
                Dim dong As DataRow = dtSet.Tables(s_tblNguoiDung).Rows(listNSD.SelectedIndex)
                dong("fullname") = user.FullName
                dong("ghichu") = user.GhiChu
                dong("nhom_id") = user.Nhom_ID
                If (trangThaiSau = True) Then
                    dong("isAdmin") = True
                Else
                    dong("isAdmin") = False
                End If
            End If
        End If
    End Sub
    Private Sub cboBan_SelectedValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboBan.SelectedValueChanged
        If (cboBan.SelectedIndex <> -1) Then
            CapNhatLaiCheckQuyen()
        End If
    End Sub
    Public Sub New()

        ' This call is required by the Windows Form Designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
    End Sub
#End Region

#Region "Context Menu"
    Private Sub btThayDoiPassword_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btThayDoiPassword.Click
        If (listNSD.SelectedIndex <> -1) Then
            'hien ra form Thay doi password
            Dim f As New frmPassword(Me)
            f.ShowDialog()
        End If
    End Sub

    'Private Sub btXoaNSDRaKhoiCSDL_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btXoaNSD.Click
    '    'kiem tra xem co phai la user hien thoi

    '    'lay ra ma nguoi su dung
    '    Dim user As New CNguoiSuDung()
    '    user.User_ID = listNSD.SelectedValue
    '    user.LoginName = listNSD.Text.Trim()
    '    If (user.LoginName = sUserName) Then
    '        MessageBox.Show("Không thể xóa vì người dùng này vẫn đang sử dụng!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error)
    '        Exit Sub
    '    End If
    '    'xac nhan xem co phai la muon xoa
    '    Dim result As DialogResult = MessageBox.Show("Bạn muốn xóa người dùng này?" & user.LoginName & "' ?", "Xác nhận xóa", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
    '    If result = Windows.Forms.DialogResult.Yes Then
    '        'doan nay se them con tro chuot cho vao
    '        Me.Cursor = Cursors.WaitCursor

    '        'xoa trong co so du lieu
    '        If (user.SetHideNSD(True) = True) Then
    '            MessageBox.Show("Xóa thành công!", "Thông báo", MessageBoxButtons.OK)
    '            'xoa trong bang tblNSD
    '            dtSet.Tables(s_tblNguoiDung).Rows(listNSD.SelectedIndex).Item("IsHide") = True
    '            'cap nhat lai dataset
    '            dtSet.AcceptChanges()
    '        Else
    '            MessageBox.Show("Xóa không thành công. Lỗi", "Thông báo", MessageBoxButtons.OK)
    '        End If
    '        Me.Cursor = Cursors.Arrow
    '    End If
    'End Sub

    Private Sub btXoaNSD_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btXoaNSD.Click
        'kiem tra xem co phai la user hien thoi
        

        'lay ra ma nguoi su dung
        Dim user As New CNguoiSuDung()
        user.User_ID = listNSD.SelectedValue
        user.LoginName = listNSD.Text.Trim()
        If (user.LoginName = sUserName) Then
            MessageBox.Show("Không thể xóa vì đang đăng nhập!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End If
        'xac nhan xem co phai la muon xoa
        If (MessageBox.Show("Có thực sự muốn xóa '" & user.LoginName & "' ?", "Xác nhận xóa", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes) Then
            'doan nay se them con tro chuot cho vao
            Me.Cursor = Cursors.WaitCursor
            Dim strSQL As String = "select isHide from NguoiDung where user_id = " + user.User_ID.ToString()
            Dim value As Boolean = Boolean.Parse(XL_DULIEU.LayGiaTri(strSQL).ToString())
            'Nếu đã hide mà vẫn xóa thì sẽ xóa hẳn
            If value Then
                If (CNguoiSuDung.XoaNSD(user.User_ID)) Then
                    MessageBox.Show("Xóa thành công!", "Thông báo", MessageBoxButtons.OK)
                    'xoa trong bang tblNSD
                    If chkHienThiTatCa.Checked Then
                        dtSet.Tables(s_tblNguoiDung).Rows(listNSD.SelectedIndex).Delete()
                        'cap nhat lai dataset
                        dtSet.AcceptChanges()
                    End If
                Else
                    MessageBox.Show("Xóa không thành công.", "Thông báo", MessageBoxButtons.OK)
                End If
            Else
                'xoa trong co so du lieu
                If (user.SetHideNSD(True)) Then
                    MessageBox.Show("Xóa thành công!", "Thông báo", MessageBoxButtons.OK)

                    'xoa trong bang tblNSD
                    If chkHienThiTatCa.Checked Then
                        dtSet.Tables(s_tblNguoiDung).Rows(listNSD.SelectedIndex).Delete()
                        'cap nhat lai dataset
                        dtSet.AcceptChanges()
                    End If
                Else
                    MessageBox.Show("Xóa không thành công.", "Thông báo", MessageBoxButtons.OK)
                End If
            End If
            Me.Cursor = Cursors.Arrow
        End If
    End Sub

    Private Sub btQuanLyThongTinNhom_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btQuanLyThongTinNhom.Click
        Dim f As New frmQuanLyNhom(Me)
        f.ShowDialog()
    End Sub
#End Region

#Region "Lam theo bang s_tblNguoiDung"
    Public Sub LayDanhSachNSD()
        ' Neu da ton tai datatable roi thi delete ra khoi dataset
        If dtSet.Tables(s_tblNguoiDung) Is Nothing Then
            'Khoi tao datatable
            Dim tbl As DataTable = New DataTable(s_tblNguoiDung)
            'them vao dataset o tren
            dtSet.Tables.Add(tbl)
        Else
            dtSet.Tables(s_tblNguoiDung).Clear()
        End If

        'Tao truy van
        Dim sSelect As String = "Select * from " + s_tblNguoiDung

        If chkHienThiTatCa.Checked = False Then
            sSelect += " where isHide = 0"
        End If

        If XL_DULIEU.LayDuLieuRaBang(sSelect, dtSet.Tables(s_tblNguoiDung)) Then
            'hien thi du lieu len listbox
            listNSD.ValueMember = "user_id"
            listNSD.DisplayMember = "loginname"
            listNSD.DataSource = dtSet.Tables(s_tblNguoiDung)
            listNSD.Update()

            'bind du lieu vao cac control
            If txtFullName.DataBindings.Count = 0 Then
                txtFullName.DataBindings.Add("Text", dtSet.Tables(s_tblNguoiDung), "fullname")
            End If

            If txtChiTiet.DataBindings.Count = 0 Then
                txtChiTiet.DataBindings.Add("Text", dtSet.Tables(s_tblNguoiDung), "GhiChu")
            End If
        Else
            MessageBox.Show("Không đọc được dữ liệu", "Thông báo", MessageBoxButtons.OKCancel, MessageBoxIcon.Information)
        End If
    End Sub

    Public Sub LayDanhSachCacNhomQuyen()
        'lay danh sach cac nhom quyen trong CSDl
        Dim dbNhom As DataTable = New DataTable(s_tblNhom)
        Dim dbNhom_Menu As DataTable = New DataTable(s_tblNhomMenu)
        Dim strSQLNhom As String = "Select * from " + s_tblNhom
        Dim strSQLNhom_Menu As String = "Select nm.Nhom_ID,nm.Menu_ID,m.MenuName from " + s_tblNhomMenu + " nm, " + s_tblMenu + " m where nm.Menu_ID = m.Menu_ID"
        If (XL_DULIEU.LayDuLieuRaBang(strSQLNhom, dbNhom) _
            And XL_DULIEU.LayDuLieuRaBang(strSQLNhom_Menu, dbNhom_Menu)) Then
            'them cac Table vao dataset o tren
            dtSet.Tables.Add(dbNhom)
            dtSet.Tables.Add(dbNhom_Menu)

            'hien thi du lieu len comboBox
            cboBan.ValueMember = "Nhom_id"
            cboBan.DisplayMember = "TenNhom"
            cboBan.DataSource = dtSet.Tables(s_tblNhom)
        Else
            MessageBox.Show("Không đọc được dữ liệu", "Thông báo", MessageBoxButtons.OKCancel, MessageBoxIcon.Information)
        End If
    End Sub

    Public Sub LayDanhSachCacQuyen()
        'lay danh sach cac nhom quyen trong CSDL
        Dim tbl As DataTable = New DataTable(s_tblMenu)
        If (XL_DULIEU.LayDuLieuRaBang("Select * from " + s_tblMenu, tbl) = True) Then
            'them vao Dataset
            dtSet.Tables.Add(tbl)
            'tao ra bang Temp chi dung de hien thi tren datagrid
            tempGirdMenu.Columns.Add("cCheck", Type.GetType("System.Boolean"))
            tempGirdMenu.Columns.Add("cTenMenu", Type.GetType("System.String"))
            'hien thi du lieu len datagrid
            For Each dong As DataRow In dtSet.Tables(s_tblMenu).Rows
                'them vao danh muc
                Dim newRow As DataRow = tempGirdMenu.NewRow()
                newRow(0) = False
                newRow(1) = dong(1)
                tempGirdMenu.Rows.Add(newRow)
            Next
            'hien thi du lieu
            gridMenu.DataSource = tempGirdMenu
        Else
            MessageBox.Show("Không đọc được dữ liệu", "Thông báo", MessageBoxButtons.OKCancel, MessageBoxIcon.Information)
        End If
    End Sub

    Public Sub CapNhatLaiCheckQuyen()
        'xoa het nhung cai da chon truoc do
        For Each d As DataRow In tempGirdMenu.Rows
            d(0) = False
        Next
        Dim maNhom As Integer = cboBan.SelectedValue
        'lay ra cac menu duoc phep truy cap
        Dim menus As New ArrayList()
        For Each dong As DataRow In dtSet.Tables(s_tblNhomMenu).Select("nhom_id =" & maNhom.ToString())
            menus.Add(dong(2))
        Next
        'set check cho cac menu
        For Each s As Object In menus
            For i As Integer = 0 To tempGirdMenu.Rows.Count - 1
                If (tempGirdMenu.Rows(i)("cTenMenu") = s.ToString.Trim()) Then
                    tempGirdMenu.Rows(i)("cCheck") = True
                End If
            Next
        Next
        gridMenu.Update()
    End Sub

    Public Sub CapNhatTrangThai(ByVal maNSD As Integer)
        Try
            'lay ra ma nhom cua nguoi su dung
            Dim dongThongTin As DataRow = dtSet.Tables(s_tblNguoiDung).Select("user_id=" & maNSD)(0)
            cboBan.SelectedValue = dongThongTin("nhom_id")
            CapNhatLaiCheckQuyen()
            If dongThongTin("isAdmin") = True Then
                chkAdmin.Checked = True
            ElseIf dongThongTin("isAdmin") = False Then
                chkAdmin.Checked = False
            End If
            If Boolean.Parse(dongThongTin("isHide")) = False Then
                contextMenuNSD.Items("KhôiPhụcLạiToolStripMenuItem").Visible = False
            Else
                contextMenuNSD.Items("KhôiPhụcLạiToolStripMenuItem").Visible = True
            End If
        Catch ex As Exception
            
        End Try
    End Sub

    Public Sub HienThi()
        LayDanhSachCacNhomQuyen()
        LayDanhSachCacQuyen()
        LayDanhSachNSD()
    End Sub
#End Region

#Region "Phim tat"
    'Private Sub listNSD_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles listNSD.KeyDown
    '    If (e.KeyCode = Keys.F1) Then
    '        Dim frm As frmThemNSD = New frmThemNSD(Me)
    '        frm.ShowDialog()
    '    End If
    '    If (e.KeyCode = Keys.F2) Then
    '        capNhatNSD()
    '    End If
    'End Sub
#End Region

    Private Sub frmMain_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown
        Select Case e.KeyCode
            Case Keys.F1
                Dim frm As frmThemNSD = New frmThemNSD(Me)
                frm.ShowDialog()
            Case Keys.F2
                capNhatNSD()
            Case Keys.Escape
                Me.Close()
        End Select
    End Sub

    Private Sub chkHienThiTatCa_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkHienThiTatCa.CheckedChanged
        LayDanhSachNSD()
    End Sub

    Private Sub listNSD_DrawItem(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DrawItemEventArgs) Handles listNSD.DrawItem
        Try
            listNSD.DrawMode = DrawMode.OwnerDrawFixed

            Dim brText As Brush
            ' Draw the background of the ListBox control for each item.
            e.DrawBackground()


            Dim objDT As DataRowView = Me.listNSD.Items.Item(e.Index)
            Dim loginname As String = objDT.Row.Item(1).ToString()
            Dim strSQL As String = "select isHide from NguoiDung where loginname = N'" + loginname + "'"
            Dim value As Boolean = Boolean.Parse(XL_DULIEU.LayGiaTri(strSQL).ToString())
            If (e.State And DrawItemState.Selected) = DrawItemState.Selected Then
                brText = Brushes.White
            ElseIf value = True Then
                brText = Brushes.Gray
            Else
                brText = Brushes.Blue
            End If

            If value = True Then
                e.Graphics.DrawString(loginname + " - Đã xóa", Me.listNSD.Font, brText, e.Bounds.X + 5, e.Bounds.Y)
            Else
                e.Graphics.DrawString(loginname, Me.listNSD.Font, brText, e.Bounds.X + 5, e.Bounds.Y)
            End If

            
           
        Catch ex As Exception

        End Try
    End Sub

    Private Sub KhôiPhụcLạiToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles KhôiPhụcLạiToolStripMenuItem.Click
        'lay ra ma nguoi su dung
        Dim user As New CNguoiSuDung()
        user.User_ID = listNSD.SelectedValue
        user.LoginName = listNSD.Text.Trim()
        If user.SetHideNSD(False) Then
            MessageBox.Show("Khôi phục thành công!")
        Else
            MessageBox.Show("Khôi phục không thành công. Lỗi!", "Thông báo", MessageBoxButtons.OK)
        End If
        Dim dr As DataRow = dtSet.Tables(s_tblNguoiDung).Select("user_id=" & user.User_ID)(0)
        dr("isHide") = False
        dr.AcceptChanges()

    End Sub

    Private Sub btnThemNhom_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnThemNhom.Click
        Dim f As New frmThemNhom(Me)
        f.ShowDialog()
    End Sub
End Class
